const app = getApp();
const { apiInstance, moment } = app;
import { setUserInfo, getUserInfo } from '../../utils/store';
const trainType = wx.getStorageSync('trainType');

Page({
  data: {
    showCreate: false,
    baseUrl: app.globalData.baseUrl,
    baseDomain: app.globalData.baseDomain,
    examId: 0,
    titleMsg: "",
    questionIndex: 0,
    exameInfo: {},
    question: [],
    passBlockAnimate: "",
    imageUpShow: true,
    imageZhengMian: '',
    imageFanMian: "",
    animation: "",
    currentExam: null,
    showKaoShiQm:false,
    isSignShow: false,
    certiInfo: {}, //证件信息
    webviewUrl: '',
    showSanJiQs: false,
    needSign: true,
    passFlag:false,
    isZhengJianKs:false,
    windowHeight:'',
    customBar:'',
    statusBar:'',
    closeSign:false,
    form: {
      name: getUserInfo()?.siocCnName,
      account: getUserInfo()?.siocPhone
    },
  },
  onLoad: function (options) {
    var examId = options.examId;
    const systemInfo = wx.getSystemInfoSync();
    const custom = wx.getMenuButtonBoundingClientRect();
 
    this.setData({
      windowHeight: systemInfo.windowHeight,
      customBar: custom.bottom + custom.top - systemInfo.statusBarHeight,
      statusBar: systemInfo.statusBarHeight
    });

    this.setData({
      examId: examId,
      animation: wx.createAnimation({
        duration: 500,  // 动画持续时间为1秒
        timingFunction: 'ease-out'  // 动画效果为缓动效果
      })
    });

    this.loadData();

    //调试证书用
    //     this.data.animation.translateY(-(app.globalData.windowHeight + app.globalData.CustomBar + app.globalData.StatusBar)).step()
    // setTimeout(()=>{
    //   this.setData({  
    //     certiInfo:{},
    //     passBlockAnimate: this.data.animation.export()   //输出动画  
    //   }) 
    // },500)


  },


  getCeti() {
    let that = this;
    wx.request({
      url: that.data.baseUrl + '/v1/openApi/certificate/need/certificate/' + that.data.examId, //1793886499071180801
      method: 'POST',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {

        if (res.data.code != 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        else {
          // 返回false 不需要生成证件
          if (res.data.data) {

            that.data.animation.translateY(-(that.data.windowHeight )).step()
            setTimeout(() => {
              that.setData({
                certiInfo: res.data.data,
                passBlockAnimate: that.data.animation.export()   //输出动画  
              })
            }, 200)


          }
        }
      }
    })
  },

  closeZhengJian(){
          this.data.animation.translateY(0).step()
     
            setTimeout(() => {
              this.setData({
                passBlockAnimate: this.data.animation.export()   //输出动画  
              })
            }, 0)
  },

  //解析地址
  parseImage(imageUrl) {
    const fileName = imageUrl.split("\/");
    return {
      fileNewName: fileName[fileName.length - 1],
      originalFileName: imageUrl
    }
  },



  //提交证书
  postCeti() {
    let that = this;

    if (!this.data.imageZhengMian || !this.data.imageFanMian) {
      wx.showToast({
        title: '请上传头像',
        icon: 'none',
        duration: 3000
      });
      return
    }

    const tempArrayImage = [];
    tempArrayImage.push({
      ...this.parseImage(this.data.imageZhengMian)
    })
    tempArrayImage.push({
      ...this.parseImage(this.data.imageFanMian)
    })


    wx.request({
      url: that.data.baseUrl + '/v1/openApi/certificate/generateInternalCertificate/' + that.data.examId, //1793886499071180801
      method: 'POST',
      data: tempArrayImage,
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        if (res.data.code != 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        wx.redirectTo({
          url: '/subPages/zhengJianGl/zhengJianGl'
        })


        that.data.animation.translateY((app.globalData.windowHeight + app.globalData.CustomBar + app.globalData.StatusBar)).step()
        setTimeout(() => {
          that.setData({
            passBlockAnimate: that.data.animation.export()   //输出动画  
          })
        }, 500)
      }
    })
  },


  loadData: async function () {
    let that = this;
    
    this.setData({
      isZhengJianKs:trainType == 'SpecialOperationTraining'
    })

    wx.request({
      url: that.data.baseUrl + '/v1/openApi/staff/error/' + that.data.examId, //1793886499071180801
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      async success(res) {
        if (res.data.code != 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          });
          return;
        }

        if (res.data.data.examine.pass == 1) {

          const res1 = await apiInstance.get(`/v1/openApi/employee/search/staff/sapId/${getUserInfo().staffId}`);
          that.setData({
            form:{
              name: res1.data.staffInfo.staffName,
              account: res1.data.staffInfo.phone
            }
          })
          // if (that.data.form.name && that.data.form.account) {
          // }
          // else {
          //   //通过需要签名 先签名
          //   that.setData({
          //     isSignShow: true
          //   });
          // } //暂时不知道有什么用


          //发起三级签署
          that.setData({
            passFlag: true,
            showKaoShiQm:true,
            currentExam: res.data.data,
            showSanJiQs: trainType == 'TeamTraining',
            needSign: trainType != 'MonthlyTraining' && trainType != 'ForeignPersonnelTraining' && trainType != 'SpecialOperationTraining',
          })
         

          // 看是否需要生成证件 
          //that.getCeti()

        }

        if (res.data.data.examine.images) {
          that.setData({
            showCreate: true
          })
        }



        that.setData({
          exameInfo: res.data.data.examine,
          question: res.data.data.questions
        });
      }, fail(res) {
        console.log(res)
        wx.showToast({
          title: '获取错题失败，请联系管理人员！',
          icon: 'none',
          duration: 3000
        });
      }
    });
  },


  kaoShiClick(){
      //如果有姓名 和手机号 直接调用接口不需要填
      if (this.data.form.name && this.data.form.account) {
        this.doSubmit();
      }
      else {
        //通过需要签名 先签名
        this.setData({
          isSignShow: true
        });
      }
  },


  //发起三级签署 
  //**
  /* 
  * @param {
  * } data  当前考试的信息
  */
  async faQiSanJiQs() {
    try {
      const bigdata = this.data.currentExam;
      //如果是班组级培训 说明3次培训都已经完成了 验证一下 是否通过考试
      if (trainType == 'TeamTraining') {
        //工厂级别考试
        const gongChangKs = await apiInstance.post(`/v1/openApi/staff/myCourse`, {
          projectType: 'MonthlyTrainingPlan',
          pass: true,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`
        })


        //车间级别考试
        const cheJianKs = await apiInstance.post(`/v1/openApi/staff/myCourse`, {
          projectType: 'WorkshopTraining',
          pass: true,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`
        })

        for (let gongChangItem of gongChangKs.rows) {
          let { data } = await apiInstance.post(`/v1/openApi/staff/pass/examine/${gongChangItem.id}/${gongChangItem.courseList[0].key}/${getUserInfo().staffId}`)
          gongChangItem.examResult = data;
        }

        for (let cheJianItem of cheJianKs.rows) {
          let { data } = await apiInstance.post(`/v1/openApi/staff/pass/examine/${cheJianItem.id}/${cheJianItem.courseList[0].key}/${getUserInfo().staffId}`)
          cheJianItem.examResult = data;
        }
        //找到考试通过的
        const gongChangeFindOne = gongChangKs.rows.find(item => item.examResult.pass == 1)
        const cheJianFindOne = cheJianKs.rows.find(item => item.examResult.pass == 1)


        //当前考试信息获取课程信息 班组级
        const banZuKs = await apiInstance.post(`/v1/openApi/staff/myCourse`, {
          trainId: bigdata.examine.trainId,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`,
          projectType: 'TeamTraining'
        })
        const banZuKsFindOne = banZuKs.rows[0]
        banZuKsFindOne.examResult = bigdata;

        if (gongChangeFindOne && cheJianFindOne) {
          //发起三级卡签名
          gongChangeFindOne.startTime

          const trainDuration1 = moment(gongChangeFindOne.endTime).diff(moment(gongChangeFindOne.startTime), 'hours')
          const trainDuration2 = moment(cheJianFindOne.endTime).diff(moment(cheJianFindOne.startTime), 'hours')
          const trainDuration3 = moment(banZuKsFindOne.endTime).diff(moment(banZuKsFindOne.startTime), 'hours')
          
          const params = {
            staffId: getUserInfo().staffId,
            studentName: getUserInfo().siocCnName,
            studentTel: getUserInfo().siocPhone,
            teacherSapId1: gongChangeFindOne.teacher,
            teacherSapId2: cheJianFindOne.teacher,
            teacherSapId3: banZuKsFindOne.teacher,
            trainBeginTime1: moment(gongChangeFindOne.startTime).format('YYYY-MM-DD HH'),
            trainBeginTime2: moment(cheJianFindOne.startTime).format('YYYY-MM-DD HH'),
            trainBeginTime3: moment(banZuKsFindOne.startTime).format('YYYY-MM-DD HH'),
            trainCreateBy: gongChangeFindOne.createBy,
            trainDuration1: gongChangeFindOne.trainingDuration,
            trainDuration2: cheJianFindOne.trainingDuration,
            trainDuration3: banZuKsFindOne.trainingDuration,
            trainEndTime1: moment(gongChangeFindOne.endTime).format('YYYY-MM-DD HH'),
            trainEndTime2: moment(cheJianFindOne.endTime).format('YYYY-MM-DD HH'),
            trainEndTime3: moment(banZuKsFindOne.endTime).format('YYYY-MM-DD HH'),
            redirectUrl:encodeURIComponent(this.data.baseDomain+'/dcp-t/#/webView?random='+new Date().getTime())
          };

          const res = await app.apiInstance.post(`/esign/wx/signThree`, params)
          wx.navigateTo({
            url: `/pages/comWebView/comWebView?url=${encodeURIComponent(res.data)}`
          });
        }
      }
    }
    catch (err) {
      console.log('err', err)
      wx.showModal({
        title: '提示',
        content: '发起三级卡信息失败，请尝试重新点击按钮或联系管理人员！',

        success: function (res) {
        
        }
      })
    }
  },


  nameChange(e) {
    this.setData({
      ['form.name']: e.detail.value
    })
  },
  numAccount(e) {
    this.setData({
      ['form.account']: e.detail.value
    })
  },

  async doSubmit() {
    if (!this.data.form.name) {
      wx.showToast({
        title: '请输入姓名！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if (!this.data.form.account) {
      wx.showToast({
        title: '请输入手机号！',
        icon: 'none',
        duration: 3000
      });
      return
    }

    

    setUserInfo(Object.assign({}, getUserInfo(), { siocPhone: this.data.form.account }))
    //调用签名接口
     //触发三级签署
   //  this.faQiSanJiQs();

   

    const res = await app.apiInstance.post(`/v1/openApi/staff/examines/${this.data.examId}?account=${this.data.form.account}&name=${this.data.form.name}&redirectUrl=${encodeURIComponent(this.data.baseDomain+'/#/webView?random='+new Date().getTime())}`, {...this.data.form})

    if (res.data) {
      this.setData({
        isSignShow: false,
        closeSign: true
      })
      console.log('res.data', res.data)
      wx.navigateTo({
        url: `/pages/comWebView/comWebView?url=${encodeURIComponent(res.data)}`
      });

    }
    
   
   
    

  },


  sanJiQsClick() {
    this.faQiSanJiQs();
  },

  zhengJianClick(){
    this.getCeti();
  },

  doWebviewClose() {
    this.setData({
      webviewUrl: ''
    })
  },


  chongXinSc() {
    this.selectComponent('#shangChuanImg').uploadImages()
  },

  preImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的链接/路径
      urls: [e.currentTarget.dataset.url]
    })
  },


  //图片上传回调
  imageUpload(e) {

    const that = this

    this.setData({
      imageUpShow: false,
      imageZhengMian: "",
      imageFanMian: ""
    })
    wx.nextTick(() => {

      that.drawPosterZhengMian({ uploadImage: e.detail }).then(res => {
        wx.uploadFile({
          url: app.globalData.fileUrl + '/common/picUpload',
          filePath: res.tempFilePath,
          name: 'file',
          success(result) {
            let fileInfo = JSON.parse(result.data);
            const imageUrl = `${app.globalData.fileUrl}/common/preview?image=${fileInfo.fileName}`

            that.setData({
              imageZhengMian: imageUrl
            })
          }
        })


      });

      that.drawPosterFanMian().then(res => {
        wx.uploadFile({
          url: app.globalData.fileUrl + '/common/picUpload',
          filePath: res.tempFilePath,
          name: 'file',
          success(result) {
            let fileInfo = JSON.parse(result.data);
            const imageUrl = `${app.globalData.fileUrl}/common/preview?image=${fileInfo.fileName}`
            that.setData({
              imageFanMian: imageUrl
            })
          }
        })


      })
    });

  },

  zhengJianSubmit() {
    this.postCeti()
  },

  preClick: function () {
    if (this.data.questionIndex > 0) {
      this.setData({
        questionIndex: (this.data.questionIndex - 1)
      })
    }
    console.log(this.data.questionIndex)
  },
  nextClick: function () {
    if (this.data.questionIndex < (this.data.question.length - 1)) {
      this.setData({
        questionIndex: (this.data.questionIndex + 1)
      })
    }
  },
  summitClick: function () {
    console.log(this.data.question);
  },
  checkChange: function (e) {
    // 更新数据以反映新的选中项  
    let questionList = this.data.question;
    let questionIndex = this.data.questionIndex;
    const question = questionList[questionIndex];
    for (let i = 0; i < question.answer.length; ++i) {
      question.answer[i].checked = e.detail.value.includes(question.answer[i].keyValue);
    }
    this.setData({
      question: questionList
    });
  },
  okClick: function () {
    var that = this;
    console.log(that.data.exameInfo.sapId)
    if (that.data.exameInfo && that.data.exameInfo.pass == 1) {
      wx.showModal({
        title: '提示',
        content: '是否确认你的成绩?',
        success: function (res) {
          if (res.confirm) {
            that.setData({
              passFlag: true
            })
            if(!that.data.needSign){
              // wx.reLaunch({
              //     url: `/pages/my-exam-list/my-exam-list?type=` + trainType
              //   })
              wx.redirectTo({
                  url: '/pages/my-signature2/my-signature2?trainId=' + that.data.exameInfo.trainId + '&projectType=' + trainType + "&examId=" + that.data.exameInfo.id + '&sapId=' + that.data.exameInfo.sapId
                })
            }
            // wx.reLaunch({
            //   url: `/pages/my-exam-home/my-exam-home`
            // })

            // wx.redirectTo({
            //   url: '/pages/my-signature/my-signature?trainId=' + that.data.exameInfo.trainId + '&courserId=' + that.data.exameInfo.courseId + "&examId=" + that.data.exameInfo.id + '&sapId=' + that.data.exameInfo.sapId
            // })
          }
        }
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '成绩未通过，是否重新考试?',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/my-exma/my-exma?trainId=' + that.data.exameInfo.trainId + '&courseId=' + that.data.exameInfo.courseId + "&examId=" + that.data.exameInfo.id + '&sapId=' + that.data.exameInfo.sapId
            })
          }
        }
      });
    }
  },

  radioChange: function (e) {
    // 更新数据以反映新的选中项  
    let questionList = this.data.question;
    let questionIndex = this.data.questionIndex;
    const question = questionList[questionIndex];
    for (let i = 0; i < question.answer.length; ++i) {
      question.answer[i].checked = question.answer[i].keyValue === e.detail.value;
    }
    this.setData({
      question: questionList
    });
  },


  /*
    * 绘制证件
  */

  // 绘制正面
  async drawPosterZhengMian({ uploadImage }) {

    const query = await new Promise((resolve, reject) => {
      wx.createSelectorQuery()
        .select('#zhengMian') // 在 WXML 中填入的 id
        .fields({
          node: true,
          size: true
        })
        .exec(res => {
          resolve(res)
        })
    })

    let canvas = query[0].node
    const ctx = canvas.getContext('2d')
    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = query[0].width * dpr
    canvas.height = query[0].height * dpr
    ctx.scale(dpr, dpr)

    ctx.clearRect(0, 0, canvas.width, canvas.height)

    let w = query[0].width * 0.9,
      h = query[0].height * 0.4,
      x = query[0].width * 0.05,
      y = query[0].height * 0.9 - 200,
      r = 10

    // 创建一个圆心渐变的对象  
    const gradient = ctx.createRadialGradient(query[0].width / 2, query[0].height / 2, 0, query[0].width / 2, query[0].height / 2, 400); // (x0,y0,r0,x1,y1,r1)  

    // 添加颜色停止点  
    gradient.addColorStop(0, '#ffffff'); // 开始颜色（在圆心处）  
    gradient.addColorStop(0.3, '#ffffff'); // 开始颜色（在圆心处）  
    gradient.addColorStop(1, '#101d61'); // 结束颜色（在边缘处）  

    // 将渐变应用到填充或描边  
    ctx.fillStyle = gradient;

    // 绘制一个圆形来使用这个渐变  
    ctx.beginPath();
    ctx.arc(query[0].width / 2, query[0].height / 2, 400, 0, Math.PI * 2); // 圆心(200,200)，半径200，从0到2π  
    ctx.fill(); // 填充圆形  

    // 绘制头像
    const image = canvas.createImage()
    image.src = uploadImage[uploadImage.length - 1]?.url

    await this.imgLoad(image)

    if(image.width>image.height){
      ctx.drawImage(image, x, 10, 70, (70/image.width)*image.height)
    }else{
      ctx.drawImage(image, x, 10, 70, (70/image.width)*image.height)
    }


    // console.log('width',image.width)
    // console.log('height',image.height)
    // ctx.drawImage(image, x, 10, 70, 84)

    // 绘制LOGO图
    const image_bg = canvas.createImage()
    image_bg.src = "../../public/img/logo.png"
    await this.imgLoad(image_bg)
    ctx.drawImage(image_bg, x + 180, 10, 80, 25)

    // 绘制证号
    ctx.beginPath()
    ctx.fillStyle = '#333'
    ctx.textAlign = 'left'
    // this.drawText(ctx, "证号", x + 85, 20, '8px  sans-serif')
    // this.drawText(ctx, this.data.certiInfo.no, x + 85, 35, 'bolder 10px sans-serif')

    this.drawText(ctx, "证号", x + 85, 50, '8px  sans-serif')
     this.drawText(ctx, this.data.certiInfo.no, x + 85, 65, 'bolder 10px sans-serif')


    //绘制姓名
    this.drawText(ctx, `姓名`, x + 85, 90, '8px sans-serif')
    this.drawText(ctx, this.data.certiInfo.name, x + 85, 105, '10px bolder sans-serif')
    // 绘制性别
    // this.drawText(ctx, `性别`, x+85, 100, '8px sans-serif')
    // this.drawText(ctx, this.data.certiInfo.sex||'', x+85, 115, '10px bolder sans-serif')
    // 绘制作业类别
    this.drawText(ctx, `作业类别`, x + 180, 50, '8px sans-serif')
    this.drawText(ctx, this.data.certiInfo.type || '', x + 180, 65, '10px bolder sans-serif')
    // 绘制操作项目
    this.drawText(ctx, `操作项目`, x + 180, 90, '8px sans-serif')
    this.drawText(ctx, this.data.certiInfo.operationItem || '', x +180, 105, '10px bolder sans-serif')

    // 绘制发证日期
    this.drawText(ctx, `发证日期`, x, 140, '8px sans-serif')
    this.drawText(ctx, this.data?.certiInfo?.firstCollarTime?.split(" ")[0], x, 155, '10px bolder sans-serif')

    // 绘制应复审日期
    this.drawText(ctx, `下次复审日期`, x, 175, '8px sans-serif')
    this.drawText(ctx, `${this.data?.certiInfo?.expirationTime?.split(" ")[0]}前`, x, 190, '10px bolder sans-serif')

    // 绘制有效期
    this.drawText(ctx, `有效期`, x + 85, 140, '8px sans-serif')
    this.drawText(ctx, `${this.data?.certiInfo?.firstCollarTime?.split(" ")[0]}至${this.data?.certiInfo?.expirationTime?.split(" ")[0]}`, x + 85, 155, '10px bolder sans-serif')
    // 绘制签发机关
    this.drawText(ctx, `发证部门`, x + 85, 175, '8px sans-serif')
    this.drawText(ctx, `应急管理部-安全部`, x + 85, 190, '10px bolder sans-serif')
    // 绘制圆角
    ctx.save()


    return wx.canvasToTempFilePath({
      canvas: canvas,
    })
  },


  // 绘制反面
  async drawPosterFanMian() {
    const query = await new Promise((resolve, reject) => {
      wx.createSelectorQuery()
        .select('#fanMian') // 在 WXML 中填入的 id
        .fields({
          node: true,
          size: true
        })
        .exec(res => {
          resolve(res)
        })
    })

    let canvas = query[0].node
    const ctx = canvas.getContext('2d')
    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = query[0].width * dpr
    canvas.height = query[0].height * dpr
    ctx.scale(dpr, dpr)
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    let w = query[0].width * 0.9,
      h = query[0].height * 0.4,
      x = query[0].width * 0.05,
      y = query[0].height * 0.9 - 200,
      r = 10

    // 创建一个圆心渐变的对象  
    const gradient = ctx.createRadialGradient(query[0].width / 2, query[0].height / 2, 0, query[0].width / 2, query[0].height / 2, 400); // (x0,y0,r0,x1,y1,r1)  

    // 添加颜色停止点  
    gradient.addColorStop(0, '#ffffff'); // 开始颜色（在圆心处）  
    gradient.addColorStop(0.3, '#ffffff'); // 开始颜色（在圆心处）  
    gradient.addColorStop(1, '#101d61'); // 结束颜色（在边缘处）  

    // 将渐变应用到填充或描边  
    ctx.fillStyle = gradient;

    // 绘制一个圆形来使用这个渐变  
    ctx.beginPath();
    ctx.arc(query[0].width / 2, query[0].height / 2, 400, 0, Math.PI * 2); // 圆心(200,200)，半径200，从0到2π  
    ctx.fill(); // 填充圆形  


    // 绘制LOGO图
    const image_bg = canvas.createImage()
    image_bg.src = "../../public/img/logo.png"
    await this.imgLoad(image_bg)
    ctx.drawImage(image_bg, x + 75, 40, 150, 47)

    // 绘制公司名称以及证件名称
    ctx.beginPath()
    ctx.fillStyle = '#333'
    ctx.textAlign = 'center'
    this.drawText(ctx, "亚太森博(广东)纸业有限公司", x + 148, 120, '14px  sans-serif')
    this.drawText(ctx, '内部使用特种设备操作证', x + 145, 150, 'bolder 18px sans-serif')


    ctx.save()
    // 绘制裁切头像区域
    ctx.beginPath()

    return wx.canvasToTempFilePath({
      canvas: canvas,
    })
  },


  // 绘制图片
  imgLoad(image) {
    return new Promise((resolve, reject) => {
      image.onload = () => {
        resolve()
      }
    })
      .catch(err => {
        console.log(err);
      })
  },
  // 绘制文字
  drawText(ctx, text, x, y, fontStyle, textProc = null) {
    ctx.font = fontStyle
    if (textProc) {
      let procText
      let { maxWidth } = textProc
      const textwidth = ctx.measureText(text).width
      if (textwidth < maxWidth) {
        procText = text
        return ctx.fillText(procText, x, y)
      }
      for (let i = 0; i < text.length; i++) {
        if (ctx.measureText(text.slice(0, i)).width > maxWidth) {
          if (textProc.line == 1) {
            procText = text.slice(0, i - 3) + '...'
            return ctx.fillText(procText, x, y)
          } else {
            procText = text.slice(0, i - 1)
            ctx.fillText(procText, x, y)
            procText = 2 * i - 4 > text.length ? text.slice(i - 1, 2 * i - 4) : text.slice(i - 1, 2 * i - 4) + '...'
            return ctx.fillText(procText, x, y + 18)
          }
        }
      }
    }
    ctx.fillText(text, x, y)
  },

});